layui.define(function(exports){
    layui.use(['layer', 'jquery','pub','shopx','table','util','form','upload'], function(){
        var layer = layui.layer
            ,pub = layui.pub
            ,shopx=layui.shopx
            ,upload=layui.upload
            ,table=layui.table
            ,util=layui.util
            ,form=layui.form
            ,$=layui.$;
        var obj = {
            postRequestNoLogin:function(url, submitType, model, callbackSucFunc, callbackFailFunc, isAsyncParam, isAlertSucParam){
                // 初始化变量
                var isAsync = false;
                var isAlertSuc = true;//true:异步；false:同步
                // 返回数据
                var result = null;
                // 请求数据对象
                if (pub.isEmpty(model)) {
                    model = {};
                }
                if (pub.isEmpty(isAsyncParam)) {
                    isAsync = false;
                } else {
                    isAsync = isAsyncParam;
                }
                if (pub.isEmpty(isAlertSucParam)) {
                    isAlertSuc = true;
                } else {
                    isAlertSuc = isAlertSucParam;
                }
                var loading = layer.load(0, {
                    time: 30*1000
                });
                setTimeout(function () {
                    $.ajax({
                        url: serverPath  + url,
                        timeout: reqTimeout,
                        contentType: "application/json",
                        // xhrFields: {
                        //   withCredentials: true
                        // },
                        // crossDomain: true,
                        type: submitType,
                        dataType: 'json',
                        // header:headerModel,
                        data: JSON.stringify(model),
                        async: isAsync,
                        success: function (data) {
                            // 成功响应
                            layer.close(loading);
                            if (data.statusCode != ERROR_CODE['SUCCESS']) {
                                // 其它业务错误
                                if (!pub.isEmpty(callbackFailFunc)) {
                                    // 有失败回调函数
                                    callbackFailFunc(data);
                                } else {
                                    // 没有失败回调函数
                                    layer.msg(data.statusDesc);
                                    return false;
                                }
                            } else {
                                if (isAlertSuc) {
                                    layer.msg('操作成功');
                                }
                                if (!pub.isEmpty(callbackSucFunc)) {
                                    callbackSucFunc(data);
                                    return false;

                                } else {
                                    result = data;
                                    return result;
                                }
                            }
                        },
                        complete: function (XMLHttpRequest, status) {
                            layer.close(loading);
                            if (status == "timeout") {
                                layer.msg('请求超时');
                                return false;
                            }
                        },
                        error: function (data) {
                            layer.close(loading);
                            layer.msg('对不起，系统开小差了');
                            return false;
                        }
                    });
                }, 200);
            },
            postRequest:function(url, submitType, model, callbackSucFunc, callbackFailFunc, isAsyncParam, isAlertSucParam){
                // 获取登录用户基本信息
                var user = shopx.getUserInfo();
                if (pub.isEmpty(user)) {
                    location.href = localPath + "/login.html?msg=会话失效了，请您重新登录";
                }
                // 初始化变量
                var isAsync = false;//true:异步；false:同步
                var isAlertSuc = false;

                // 返回数据
                var result = null;
                // 请求数据对象
                if (pub.isEmpty(model)) {
                    model = {};
                }
                if (pub.isEmpty(isAsyncParam)) {
                    isAsync = false;
                } else {
                    isAsync = isAsyncParam;
                }
                if (pub.isEmpty(isAlertSucParam)) {
                    isAlertSuc = false;
                } else {
                    isAlertSuc = isAlertSucParam;
                }

                if (pub.isEmpty(submitType)) {
                    submitType = 'POST'
                }

                var hmac = shopx.signRequest(); // 签名
                var headerModel = {
                    "hmac": hmac
                }
                var reqPath = serverPath + "/";
                var loading = layer.load(0, {
                    time: 30*1000
                });
                setTimeout(function () {
                    $.ajax({
                        url: reqPath + url,
                        timeout: reqTimeout,
                        contentType: "application/json",
                        type: submitType,
                        dataType: 'json',
                        headers: headerModel,
                        data: JSON.stringify(model),
                        async: isAsync,
                        success: function (data) {
                            layer.close(loading);
                            // 成功响应
                            if (data.statusCode != ERROR_CODE['SUCCESS']) {
                                if (data.statusCode == ERROR_CODE['TOKEN_INVALIDATE']
                                    || data.statusCode == ERROR_CODE['TOKEN_ERROR']) {
                                    // 会话失效
                                    // location.href = localPath + "/login.html?msg=会话失效了，请您重新登录";
                                    return false;
                                } else {
                                    // 其它业务错误
                                    if (!pub.isEmpty(callbackFailFunc)) {
                                        // 有失败回调函数
                                        callbackFailFunc(data);
                                    } else {
                                        // 没有失败回调函数
                                        layer.msg(data.statusDesc);
                                        return false;
                                    }
                                }
                            } else {
                                if (isAlertSuc) {
                                    layer.msg("操作成功");
                                }
                                if (!pub.isEmpty(callbackSucFunc)) {
                                    layer.close(loading);
                                    callbackSucFunc(data);
                                    return false;
                                } else {
                                    layer.close(loading);
                                    result = data;
                                    return result;
                                }
                            }
                        },
                        complete: function (XMLHttpRequest, status) {
                            layer.close(loading);
                            if (status == "timeout") {
                                layer.msg("请求超时");
                                return false;
                            }
                        },
                        error: function (data) {
                            layer.close(loading);
                            layer.msg("对不起，系统开小差了");
                            return false;
                        }
                    });
                }, 200);
            },
            uploadImgs:function(imgId,url,fileMultiple,fileSize,acceptFile,fileExts,fileNum,fileType){
                if(pub.isEmpty(fileSize)){
                    fileSize = 102400;
                }
                if(pub.isEmpty(acceptFile)){
                    acceptFile = 'file';
                }
                if(pub.isEmpty(fileMultiple)){
                    fileMultiple = false;
                }
                var headerModel = {
                    "hmac": ossKey
                }
                layui.upload.render({
                    elem: "#"+imgId+'_upload',
                    url: serverOssPath+url+"?cpId=material",
                    headers:headerModel,
                    multiple: fileMultiple,//是否允许多文件上传
                    size: fileSize,//设置文件最大可允许上传的大小，单位 KB
                    accept: acceptFile,//指定允许上传时校验的文件类型
                    // acceptMime: acceptMime,//规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表
                    exts: fileExts,//允许上传的文件后缀
                    number: fileNum,//设置同时可上传的文件数量，一般配合 multiple 参数出现
                    field:fileType,
                    done: function(res){
                        if (res.statusCode != ERROR_CODE['SUCCESS']) {
                            $('#ID-upload-demo-text').html('');
                            if (res.statusCode == ERROR_CODE['TOKEN_INVALIDATE']
                                || res.statusCode == ERROR_CODE['TOKEN_ERROR']) {
                                console.info("会话失效了，请重新登录");
                                location.href = localPath + "/login.html?msg=会话失效了，请您重新登录";
                                return false;
                            } else {
                                layer.msg('上传失败');
                            }
                        }else{
                            if(!fileMultiple){
                                //单个文件
                                $('#'+imgId+"_img").attr('src', serverImgPath+res.rspData.split(":")[0]);
                                $("#"+imgId).val(res.rspData.split(":")[0]);
                            }else{
                                var img = res.rspData;
                                var imgHtml = '<div style="width: 15%;float: left" id="div_'+imgId+'_'+res.rspData.split(":")[1]+'"><img  onclick="albumImgs(\''+imgId+'\')" src="'+ serverImgPath+img.split(":")[0] +'" alt="'+ img.split(":")[1] +'" style="width: 100px; height: 100px;margin-right: 15px;margin-top: 15px;"/>'+
                                '<input type="hidden" id="'+imgId+'_'+res.rspData.split(":")[1]+'" value="'+img.split(":")[0]+'"/><div style="text-align: left"><button type="button" style="width: 100px;margin-top: 10px;" class="layui-btn layui-btn-primary" lay-submit="" onclick="delImg(\''+imgId+'\',\''+res.rspData.split(":")[1]+'\')">删除</button></div></div>';
                                $('#'+imgId+"_img").append(imgHtml);
                                $("#"+imgId).val(img.split(":")[0]+","+$("#"+imgId).val());
                            }
                        }
                    },
                    error: function(){
                        layer.msg('上传失败');
                        return false;
                    },
                    // 进度条
                    progress: function(n, elem, e){
                        layui.element.progress(imgId+'_process', n + '%');
                        if(n == 100){
                            layer.msg('上传完毕', {icon: 1});
                        }
                    }
                });
            },
            uploadFile:function(fileId,url,fileMultiple,fileSize,acceptFile,fileExts,fileNum,fileType){
                if(pub.isEmpty(fileSize)){
                    fileSize = 102400;
                }
                if(pub.isEmpty(acceptFile)){
                    acceptFile = 'file';
                }
                if(pub.isEmpty(fileMultiple)){
                    fileMultiple = false;
                }
                var headerModel = {
                    "hmac": ossKey
                }
                layui.upload.render({
                    elem: "#"+fileId+'_upload',
                    url: serverOssPath+url+"?cpId=material",
                    headers:headerModel,
                    multiple: fileMultiple,//是否允许多文件上传
                    size: fileSize,//设置文件最大可允许上传的大小，单位 KB
                    accept: acceptFile,//指定允许上传时校验的文件类型
                    // acceptMime: acceptMime,//规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表
                    exts: fileExts,//允许上传的文件后缀
                    number: fileNum,//设置同时可上传的文件数量，一般配合 multiple 参数出现
                    field:fileType,
                    done: function(res){
                        if (res.statusCode != ERROR_CODE['SUCCESS']) {
                            $('#ID-upload-demo-text').html('');
                            if (res.statusCode == ERROR_CODE['TOKEN_INVALIDATE']
                                || res.statusCode == ERROR_CODE['TOKEN_ERROR']) {
                                console.info("会话失效了，请重新登录");
                                location.href = localPath + "/login.html?msg=会话失效了，请您重新登录";
                                return false;
                            } else {
                                layer.msg('上传失败');
                            }
                        }else{
                            var file = res.rspData;
                            var fileHtml = '<div style="width: 20%;float: left" id="div_'+fileId+'_'+res.rspData.split(":")[1]+'"><img src="./images/file.png" onclick="openFile(\''+res.rspData.split(":")[0]+'\')" style="width: 80px; height: 80px;margin-right: 15px;margin-top: 15px;" onclick=""/>'+
                                '<input type="hidden" id="'+fileId+'_'+res.rspData.split(":")[1]+'" value="'+file.split(":")[0]+'"/><div style="text-align: left"><button type="button" style="width: 100px;margin-top: 10px;" class="layui-btn layui-btn-primary" lay-submit="" onclick="delImg(\''+fileId+'\',\''+res.rspData.split(":")[1]+'\')">删除</button></div></div>';
                            $('#'+fileId+"_file").append(fileHtml);
                            $("#"+fileId).val(file.split(":")[0]+","+$("#"+fileId).val());
                        }
                    },
                    error: function(){
                        layer.msg('上传失败');
                        return false;
                    },
                    // 进度条
                    progress: function(n, elem, e){
                        layui.element.progress(fileId+'_process', n + '%');
                        if(n == 100){
                            layer.msg('上传完毕', {icon: 1});
                        }
                    }
                });
            },
            getUserFunc:function(){
                //获取登录用户有权限的页面元素
                var userFunc =  layui.data(SYS_SESSION['USER_FUNC']).USER_FUNC;
                if(pub.isEmpty(userFunc)){
                    var user = shopx.getUserInfo();
                    var model = {
                        userId: user.userId,
                        urlType: '2'
                    }
                    this.postRequest("/sysUrl/getUrlByUserId", 'POST', model, function suc(data) {
                        // console.info("func:"+JSON.stringify(data));
                        layui.data(SYS_SESSION['USER_FUNC'], {
                            key: SYS_SESSION['USER_FUNC'],
                            value: data.rspData});
                        return data.rspData;
                    }, null, false, false);
                }else{
                    return userFunc;
                }
            },
            getDict:function(){
                //将字典缓存写入内存
                var sysDict =  layui.data(SYS_SESSION['SYS_DICT']).SYS_DICT;
                if(pub.isEmpty(sysDict)){
                    console.info("数据库读取");
                    var model = {
                        state: '1',
                        order: " dict_code asc "
                    }
                    this.postRequest("/sysDict/queryPageList", 'POST', model, function suc(data) {
                        layui.data(SYS_SESSION['SYS_DICT'], {
                            key: SYS_SESSION['SYS_DICT'],
                            value: data.rspData.data});
                        return data.rspData.data;
                    }, null, false, false);
                }else{
                    return sysDict;
                }
            },
            clearDict:function(){
                //清空缓存重新写入
                layui.data(SYS_SESSION['SYS_DICT'],null);
                var model = {
                    state: '1',
                    order: " dict_code asc "
                }
                this.postRequest("/sysDict/queryPageList", 'POST', model, function suc(data) {
                    layui.data(SYS_SESSION['SYS_DICT'], {
                        key: SYS_SESSION['SYS_DICT'],
                        value: data.rspData.data});
                    return data.rspData.data;
                }, null, false, false);
            },
            initPage:function(page){
                //初始化页面
                var cols = page.cols;
                var tableName= page.tableName;
                var qryUrl = page.qryUrl;
                var updUrl = page.updUrl;
                var addModel = page.addModel;
                var that = this;
                //分页查询
                var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                qryModel['isPage'] = "1";
                qryModel['order'] = page.orderBy;
                if (typeof page.midQueryFunc == 'function') {
                    try {
                        page.midQueryFunc(qryModel);
                    } catch (e) {
                        return false;
                    }
                }
                if(!pub.isEmpty(addModel)){
                    $.each(addModel, function(key, val) {
                        qryModel[key]=val;
                    });
                }
                // if(!page.initQry){
                //     //默认不查询
                //     console.info("默认不查询");
                //     return;
                // }
                var pageTable = table.render({
                    elem: '#'+tableName
                    , url: serverPath + qryUrl
                    , headers: {hmac: shopx.signRequest()}
                    , toolbar: '#tooolbarDemo'
                    , contentType: 'application/json'
                    , method: "post"
                    , where: qryModel
                    , parseData: function (res) {
                        return {
                            "code": res.statusCode,
                            "msg": res.statusDesc, //解析提示文本
                            "count": res.rspData == null ? 0 : res.rspData.iTotalDisplayRecords, //解析数据长度
                            "data": res.rspData == null ? "" : res.rspData.data //解析数据列表
                        }
                    },
                    request: {
                        pageName: "pageStart",
                        limitName: "pageLength"
                    },
                    respone: {
                        statusName: "code",
                        statusCode: '00000'
                    },
                    cols: cols
                    , page: true
                    , limits: [10, 20, 50, 100]
                    , limit: 10
                    , done: function (res, curr, count) {
                        if (res.code != ERROR_CODE['SUCCESS']) {
                            if (res.code == ERROR_CODE['TOKEN_INVALIDATE']
                                || res.code == ERROR_CODE['TOKEN_ERROR']) {
                                // 会话失效
                                // location.href = localPath + "/login.html?msg=会话失效了，请您重新登录";
                                localStorage.clear();
                                location.href = "./login.html";
                                return;
                            } else {
                                layer.msg(res.msg);
                                return;
                            }
                        } else {
                            //成功
                            return;
                        }
                    }
                    , exportDataUrl: ""
                    , exportMethod: "post"
                    , exportAction: function (table, tableIns, config, exportType) {
                    }
                });
                if(page.ifPage==false){
                    $(".layui-table-page").hide();
                }
                //字段排序
                table.on('sort('+tableName+')', function (obj) {
                    // console.info(JSON.stringify(obj));
                    var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                    qryModel['isPage'] = "1";
                    qryModel['order'] = pub.covertHump(obj.field + ' ' + obj.type);
                    // console.info(JSON.stringify(qryModel));
                    table.reload(tableName, {
                        initSort: obj,
                        page: {curr: 0},
                        where: qryModel
                    })
                    if(page.ifPage==false){
                        $(".layui-table-page").hide();
                    }
                });
                //监听行数据变化
                table.on('edit('+tableName+')', function (obj) {
                    var value = obj.value //得到修改后的值
                        , data = obj.data //得到所在行所有键值
                        , field = obj.field; //得到字段
                    var keyId = page.keyId;
                    var model = {
                    }
                    model[keyId] = obj.data[keyId];
                    model[field] = util.escape(value);
                    console.info("修改："+JSON.stringify(model));
                    that.postRequest(updUrl, 'POST', model, function suc(data) {
                        // qryModel = pub.getFormObject('conForm', 'qry_');
                        // qryModel['isPage'] = "1";
                        // qryModel['order'] = " update_time desc ";
                        // var curr = $(".layui-laypage-em").next().html();
                        // var limit = table.config.page.limit;
                        // var curr2 = 0;
                        // if (curr > 1) {
                        //     curr2 = (curr - 1) * limit;
                        // } else {
                        //     curr2 = 0;
                        // }
                        // table.reload(tableName, {
                        //     page: {curr: curr2},
                        //     where: qryModel
                        // }, null, null, 1)
                    }, null, false, true);
                    if(page.ifPage==false){
                        $(".layui-table-page").hide();
                    }
                });

                //初始化增删改查导出按钮操作
                this.initBtn(page,pageTable);
            },
            initBtn:function(page,pageTable){
                //初始化按钮
                if ($("#b_"+page.prefix+'_'+page.name+'QueryBtn').length > 0) {
                    //查询
                    this.qryPage(page);
                }
                if ($("#b_"+page.prefix+'_'+page.name+'AddBtn').length > 0) {
                    //新增
                    this.addForm(page);
                }
                if ($("#b_"+page.prefix+'_'+page.name+'UpdateBtn').length > 0) {
                    //修改
                    this.updForm(page,pageTable);
                }
                if ($("#b_"+page.prefix+'_'+page.name+'ViewBtn').length > 0) {
                    //明细
                    this.viewForm(page);
                }
                if ($("#b_"+page.prefix+'_'+page.name+'DelBtn').length > 0) {
                    //删除
                    this.delForm(page);
                }
                if ($("#b_"+page.prefix+'_'+page.name+'ExpBtn').length > 0) {
                    //导出
                    this.expForm(page);
                }
            },
            qryPage:function(page){
                //查询
                $("#b_"+page.prefix+'_'+page.name+'QueryBtn').click(function () {
                    if(!pub.isEmpty(page.beforeQueryFunc)){
                        if (typeof page.beforeQueryFunc == 'function') {
                            try {
                                page.beforeQueryFunc();
                            } catch (e) {
                                return false;
                            }
                        }
                    }
                    var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                    qryModel['isPage'] = "1";
                    qryModel['order'] = page.orderBy;
                    if (typeof page.midQueryFunc == 'function') {
                        try {
                            page.midQueryFunc(qryModel);
                        } catch (e) {
                            return false;
                        }
                    }
                    if(!pub.isEmpty(page.addModel)){
                        $.each(page.addModel, function(key, val) {
                            qryModel[key]=val;
                            // console.log("Key: " + key + ", Value: " + val);
                        });
                    }
                    table.reload(page.tableName, {
                        page: {curr: 0},
                        where: qryModel,
                        done: function(res, curr, count){
                            if(!pub.isEmpty(page.afterQueryFunc)){
                                if (typeof page.afterQueryFunc == 'function') {
                                    try {
                                        page.afterQueryFunc(res);
                                    } catch (e) {
                                        return false;
                                    }
                                }
                            }
                        }
                    })
                    if(page.ifPage==false){
                        $(".layui-table-page").hide();
                    }
                });
            },
            addForm:function(page){
                //新增
                var that = this;
                var addHtml = shopx.genForm(page);
                $("#b_"+page.prefix+'_'+page.name+'AddBtn').click(function () {
                    layer.open({
                        type: 1,
                        title: page.title+"新增",
                        content: addHtml,
                        minStack: true,
                        area: ['60%', '60%'],
                        maxmin: true,
                        btn: ['确认', '关闭'],
                        id: page.name+"_add",
                        yes: function (index, layero) {
                            form.on('submit(addSubmit)', function (data) {
                                //提交表单
                                if(!pub.isEmpty(page.midAddFunc)){
                                    if (typeof page.midAddFunc == 'function') {
                                        try {
                                            page.midAddFunc(data);
                                        } catch (e) {
                                            return false;
                                        }
                                    }
                                }
                                let newModel = JSON.stringify(Object.fromEntries(Object.entries(data.field).map(([key, value]) => [key.replace('f_'+page.prefix+'_', ''), value])));
                                // console.info(JSON.parse(newModel));
                                that.postRequest(page.addUrl, 'POST', JSON.parse(newModel), function suc(res) {
                                    var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                                    qryModel['isPage'] = "1";
                                    qryModel['order'] = page.orderBy;
                                    table.reload(page.tableName, {
                                        page: {curr: 0},
                                        where: qryModel
                                    })
                                    layer.close(index);
                                    if(!pub.isEmpty(page.afterAddFunc)){
                                        //新增回调函数
                                        if (typeof page.afterAddFunc == 'function') {
                                            try {
                                                page.afterAddFunc(data.field);
                                            } catch (e) {
                                                return false;
                                            }
                                        }
                                    }
                                }, null, false, true);
                            });
                        },
                        btn2: function () {
                            layer.closeAll();
                        },
                        success: function (layero, index) {
                            //弹框渲染
                            // 添加form标识
                            layero.addClass('layui-form');
                            // 将保存按钮改变成提交按钮
                            layero.find('.layui-layer-btn0').attr({
                                'lay-filter': 'addSubmit',
                                'lay-submit': ''
                            });
                            form.render();
                            //重新渲染表单
                            if(!pub.isEmpty(page.beforeAddFunc)){
                                if (typeof page.beforeAddFunc == 'function') {
                                    try {
                                        page.beforeAddFunc();
                                    } catch (e) {
                                        return false;
                                    }
                                }
                            }
                        }
                    })
                });
            },
            updForm:function(page,pageTable){
                //修改
                var that = this;
                var editHtml = shopx.genForm(page);
                $("#b_"+page.prefix+'_'+page.name+'UpdateBtn').click(function () {
                    var selectRows = layui.table.checkStatus(page.tableName).data;
                    if (selectRows.length != 1) {
                        layer.msg("请选择一条数据进行编辑");
                        return false;
                    }
                    var model = {}
                    var keyId = page.keyId
                    var keyVal = "";
                    var obj = selectRows[0];
                    for (var key in obj) {
                        if(key==keyId){
                            keyVal = obj[key];
                            break;
                        }
                    }
                    model[keyId] = keyVal;
                    that.postRequest(page.detUrl, 'POST', model, function suc(data) {
                        var detRes = data;
                        layer.open({
                            title: page.title+"编辑",
                            type: 1,
                            skin: 'layui-layer-border',
                            area: ['60%', '60%'],
                            content: editHtml,
                            maxmin: true,
                            minStack: true,
                            id: page.name+"_edit",
                            btn: ['确认', '关闭'],
                            yes: function (index, layero) {
                                var idx = index;
                                form.on('submit(addSubmit)', function (data) {
                                    //提交表单
                                    // console.info(JSON.stringify(data.field));
                                    if(!pub.isEmpty(page.midUpdFunc)){
                                        if (typeof page.midUpdFunc == 'function') {
                                            try {
                                                page.midUpdFunc(data);
                                            } catch (e) {
                                                return false;
                                            }
                                        }
                                    }
                                    let newModel = JSON.stringify(Object.fromEntries(Object.entries(data.field).map(([key, value]) => [key.replace('f_'+page.prefix+'_', ''), value])));
                                    that.postRequest(page.updUrl, 'POST', JSON.parse(newModel), function suc(res) {
                                        layer.close(idx);
                                        var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                                        qryModel['isPage'] = "1";
                                        qryModel['order'] = page.orderBy;
                                        var curr = $(".layui-laypage-em").next().html();
                                        var limit = pageTable.config.page.limit;
                                        var curr2 = 0;
                                        if (curr > 1) {
                                            curr2 = (curr - 1) * limit;
                                        } else {
                                            curr2 = 0;
                                        }
                                        table.reload(page.tableName, {
                                            page: {curr: curr2},
                                            where: qryModel
                                        }, null, null, 1);

                                        if(!pub.isEmpty(page.afterUpdFunc)){
                                            if (typeof page.afterUpdFunc == 'function') {
                                                try {
                                                    page.afterUpdFunc(res);
                                                } catch (e) {
                                                    return false;
                                                }
                                            }
                                        }

                                    }, null, false, true);
                                });
                            },
                            btn2: function () {
                                layer.closeAll();
                            },
                            success: function (layero, index) {
                                //弹框渲染
                                // 添加form标识
                                layero.addClass('layui-form');
                                // 将保存按钮改变成提交按钮
                                layero.find('.layui-layer-btn0').attr({
                                    'lay-filter': 'addSubmit',
                                    'lay-submit': ''
                                });
                                var obj = data.rspData;
                                // console.info("obj:"+JSON.stringify(obj));
                                let newModel = JSON.stringify(Object.fromEntries(Object.entries(obj).map(([key, value]) => [`f_`+page.prefix+`_${key}`, value])));
                                if(!pub.isEmpty(page.beforeUpdFunc)){
                                    //需要先渲染表单后，再赋值
                                    if (typeof page.beforeUpdFunc == 'function') {
                                        try {
                                            page.beforeUpdFunc(detRes,function callbackFunc(){
                                                //渲染表单后，调用回调函数赋值
                                                form.val(page.formName, JSON.parse(newModel));
                                                form.render();
                                            });
                                        } catch (e) {
                                            return false;
                                        }
                                    }
                                }else{
                                    //直接赋值
                                    form.val(page.formName, JSON.parse(newModel));
                                    form.render();
                                }
                            }
                        });
                    }, null, false, false);
                });
            },
            viewForm:function(page){
                //明细
                var that = this;
                var editHtml = shopx.genViewForm(page);
                $("#b_"+page.prefix+'_'+page.name+'ViewBtn').click(function () {
                    var selectRows = layui.table.checkStatus(page.tableName).data;
                    if (selectRows.length != 1) {
                        layer.msg("请选择一条数据进行编辑");
                        return false;
                    }
                    var model = {}
                    var keyId = page.keyId
                    var keyVal = "";
                    var obj = selectRows[0];
                    for (var key in obj) {
                        if(key==keyId){
                            keyVal = obj[key];
                            break;
                        }
                    }
                    model[keyId] = keyVal;
                    that.postRequest(page.detUrl, 'POST', model, function suc(data) {
                        var detRes = data;
                        layer.open({
                            title: page.title+"明细",
                            type: 1,
                            skin: 'layui-layer-border',
                            area: ['60%', '60%'],
                            content: editHtml,
                            maxmin: true,
                            minStack: true,
                            id: page.name+"_edit",
                            btn: [ '关闭'],
                            success: function (layero, index) {
                                var obj = data.rspData;
                                let newModel = JSON.stringify(Object.fromEntries(Object.entries(obj).map(([key, value]) => [`f_`+page.prefix+`_${key}`, value])));
                                if(!pub.isEmpty(page.beforeViewFunc)){
                                    //需要先渲染表单后，再赋值
                                    if (typeof page.beforeViewFunc == 'function') {
                                        try {
                                            page.beforeViewFunc(detRes,function callbackFunc(){
                                                //渲染表单后，调用回调函数赋值
                                                form.val(page.formName, JSON.parse(newModel));
                                                form.render();
                                            });
                                        } catch (e) {
                                            return false;
                                        }
                                    }
                                }else{
                                    //直接赋值
                                    form.val(page.formName, JSON.parse(newModel));
                                    form.render();
                                }
                            }
                        });
                    }, null, false, false);
                });
            },
            delForm:function(page){
                //删除
                var that = this;
                $("#b_"+page.prefix+'_'+page.name+'DelBtn').click(function () {
                    var selectRows = layui.table.checkStatus(page.tableName).data;
                    if (selectRows.length <= 0) {
                        layer.msg('请至少选择一条记录');
                        return;
                    }
                    if(!pub.isEmpty(page.beforeDelFunc)){
                        if (typeof page.beforeDelFunc == 'function') {
                            try {
                                page.beforeDelFunc(selectRows);
                            } catch (e) {
                                return false;
                            }
                        }
                    }
                    layer.confirm('确认删除选中记录吗？', {
                        btn: ['确定', '取消']
                    }, function (index) {
                        that.postRequest(page.delBatchUrl, 'POST', selectRows, function suc(res) {
                            layer.close(index);
                            var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                            qryModel['isPage'] = "1";
                            qryModel['order'] = page.orderBy;;
                            table.reload(page.tableName, {
                                page: {curr: 0},
                                where: qryModel
                            });
                            if(!pub.isEmpty(page.afterDelFunc)){
                                if (typeof page.afterDelFunc == 'function') {
                                    try {
                                        page.afterDelFunc(selectRows);
                                    } catch (e) {
                                        return false;
                                    }
                                }
                            }
                        });
                    }, function () {
                    });
                });
            },
            expForm:function(page){
                //导出
                $("#b_"+page.prefix+'_'+page.name+'ExpBtn').click(function () {
                    var qryModel = pub.getFormObject(page.conName, 'q_'+page.prefix+"_");
                    qryModel['order'] = page.orderBy;
                    var urlParams = $.param(qryModel);
                    var hmac = shopx.signRequest();
                    $("#"+page.conName).attr("method", "post");
                    // console.info(serverPath + page.downloadUrl+'?hmac=' + encodeURI(hmac).replace(/\+/g, '%2B') + "&" + urlParams);
                    $("#"+page.conName).attr("action", serverPath + page.downloadUrl+'?hmac=' + encodeURI(hmac).replace(/\+/g, '%2B') + "&" + urlParams);
                    $("#"+page.conName).submit();
                });
            },
            qryRoleList:function(model,id){
                //查询角色
                this.postRequest("/sysRole/queryPageList", 'POST', model, function suc(data) {
                    $("#"+id).html('<option value="">请选择</option>');
                    $(data.rspData.data).each(function (idx, item) {
                        $("#"+id).append('<option value="'+item.roleCode+'">'+item.roleName+'</option>');
                    });
                    form.render();
                }, null, false, false);
            },
            qryOrgList:function(model,id){
                // console.info("获取qryOrgList");
                //走缓存
                // console.info("getUserInfo:"+JSON.stringify(shopx.getUserInfo()));
                var orgList = shopx.getUserInfo().orgList;
                // console.info("orgList:"+JSON.stringify(orgList));
                $(orgList).each(function (idx, item) {
                    var level = item.orgLevel;
                    // console.info("level:"+level);
                    var orgLevel = "";
                    if(level==2){
                        orgLevel = "-";
                    }else  if(level==3){
                        orgLevel = "- -";
                    }else  if(level==4){
                        orgLevel = "- - -";
                    }
                    $("#"+id).append('<option value="'+item.orgId+'">'+orgLevel+item.orgName+'</option>');
                });
                // var cacheKey = "ORG_KEY_"+user.userId;
                // var cachedData = layui.data('localCache')[cacheKey];
                // $("#"+id).html('<option value="">请选择</option>');
                // if (cachedData) {
                //     // console.info("走缓存：");
                //     $(cachedData).each(function (idx, item) {
                //         $("#"+id).append('<option value="'+item.orgId+'">'+item.orgName+'</option>');
                //     });
                // }else{
                //     // console.info("走接口");
                //     //查询角色
                //     this.postRequest("/sysOrg/selectOrgTreeList", 'POST', model, function suc(data) {
                //         layui.data('localCache', {
                //             key: cacheKey,
                //             value: data.rspData
                //         });
                //         // console.info("走接口2");
                //         $(data.rspData).each(function (idx, item) {
                //             $("#"+id).append('<option value="'+item.orgId+'">'+item.orgName+'</option>');
                //         });
                //     }, null, false, false);
                // }
                form.render();
            }
        };
        //输出模块
        exports('http',obj);
    });
});

/**
 * 删除图片
 * @param imgId
 * @param num
 * @returns {boolean}
 */
function delImg(imgId,num){
    var imgVal = layui.jquery("#"+imgId+"_"+num).val()+",";
    var imgs =layui.pub.replaceAll(layui.jquery("#"+imgId).val(),imgVal,"") ;
    layui.jquery("#"+imgId).val(imgs);
    layui.jquery("#div_"+imgId+"_"+num).remove();
    return false;
}

/**
 * 展示单个图片
 * @param imgId
 * @param src
 */
function showImg(imgId,src){
    layui.jquery("#"+imgId).attr("src",serverImgPath+src);
}

/**
 * 展示多个图片
 * @param imgId
 * @param res
 */
function showImgs(imgId,res,muilFlag,viewFlag){
    if(!muilFlag){
        //单图片
        layui.jquery("#"+imgId+"_img").attr("src",serverImgPath+res);
        layui.jquery("#"+imgId).val(serverImgPath+res);
    }else{
        //多图片
        var imgs = "";
        for(var i=0;i<res.split(",").length;i++){
            var item = res.split(",")[i];
            if(layui.pub.isEmpty(item)){
                continue;
            }
            var fileName = item.split('/').pop();
            item = item+":"+fileName.split('.').slice(0, -1).join('.');

            var btnHtml = '<button type="button" style="width: 100px;margin-top: 10px;" class="layui-btn layui-btn-primary" lay-submit="" onclick="delImg(\''+imgId+'\',\''+item.split(":")[1]+'\')">删除</button>';
            if(viewFlag){
                btnHtml = '';
            }

            var imgHtml = '<div style="width: 15%;float: left" id="div_'+imgId+'_'+item.split(":")[1]+'"><img onclick="albumImgs(\''+imgId+'\')" src="'+ serverImgPath+item.split(":")[0] +'" alt="'+ item.split(":")[1] +'" style="width: 100px; height: 100px;margin-right: 15px;margin-top: 15px;"/>'+
                '<input type="hidden" id="'+imgId+'_'+item.split(":")[1]+'" value="'+item.split(":")[0]+'"/><div style="text-align: left">'+btnHtml+'</div></div>';
            layui.jquery('#'+imgId+"_img").append(imgHtml);
            imgs+=item.split(":")[0]+",";
        }
        layui.jquery("#"+imgId).val(imgs);
    }
}

function showFiles(fileId,res,viewFlag){
    var files = "";
    for(var i=0;i<res.split(",").length;i++){
        var item = res.split(",")[i];
        if(layui.pub.isEmpty(item)){
            continue;
        }
        var fileName = item.split('/').pop();
        item = item+":"+fileName.split('.').slice(0, -1).join('.');

        var btnHtml = '<button type="button" style="width: 100px;margin-top: 10px;" class="layui-btn layui-btn-primary" lay-submit="" onclick="delImg(\''+fileId+'\',\''+item.split(":")[1]+'\')">删除</button>';
        if(viewFlag){
            btnHtml = '';
        }

        var imgHtml = '<div style="width: 20%;float: left" id="div_'+fileId+'_'+item.split(":")[1]+'">' +
            '<img onclick="openFile(\''+item.split(":")[0]+'\')" src="./images/file.png" style="width: 80px; height: 80px;margin-right: 15px;margin-top: 15px;"/>'+
            '<input type="hidden" id="'+fileId+'_'+item.split(":")[1]+'" value="'+item.split(":")[0]+'"/><div style="text-align: left">'+btnHtml+'</div></div>';
        layui.jquery('#'+fileId+"_file").append(imgHtml);
        files+=item.split(":")[0]+",";
    }
    layui.jquery("#"+fileId).val(files);
}

/**
 * 相册展示图片
 * @param imgId
 */
function albumImgs(imgId){
    //获取div下所有的图片
    var photos = new Array();
    var i =0;
    layui.jquery('#'+imgId+'_img img').each(function() {
        var src = layui.jquery(this).attr('src');
        console.info("src:"+src);
        var model = {
            "src":src
        }
        photos[i] = model;
        i++;
    });

    layer.photos({
        shade: 0.9,
        anim: 5,
        photos: {
            "data": photos
        } //格式见API文档手册页
    });
}

/**
 *
 * @param imgId
 */
function albumSingleImgs(imgId){
    //获取div下所有的图片
    var photos = new Array();
    var src = layui.jquery('#'+imgId).attr("src");
    var model={
        "src":src
    }
    photos[0] = model;
    layer.photos({
        shade: 0.9,
        anim: 5,
        photos: {
            "data": photos
        } //格式见API文档手册页
    });
}

/**
 * 打开文件
 * @param fileId
 */
function openFile(filePath){
   window.open(serverImgPath+filePath);
}